import { useEffect, useState } from 'react';
import { Table, Card, Modal, Button, message, Form, Input, Space } from 'antd';
import { enumDictPage } from '@/api/dictEnums';
import { SearchOutlined } from '@ant-design/icons';

const EnumDict = () => {
  const [form] = Form.useForm();
  
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchForm, setSearchForm] = useState({
    dictCode: "",
    size: 10,
    current: 1
  });
  const [total, setTotal] = useState(0);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalData, setModalData] = useState([]);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = (formData) => {
    setLoading(true);
    const params = formData || searchForm;
    enumDictPage(params).then(res => {
      if (res.code === '200') {
        setData(res.data.others || []);
        setTotal(res.data.total || 0);
      } else {
        message.error(res.msg || '获取数据失败');
      }
    }).catch(error => {
      message.error('请求失败: ' + error.message);
    }).finally(() => {
      setLoading(false);
    });
  };

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };
    
    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }
    
    setSearchForm(formData);
    fetchData(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      dictCode: values.dictCode || "",
      current: 1 // 重置为第一页
    };
    setSearchForm(formData);
    fetchData(formData);
  };


  const showModal = (values) => {
    setModalData(values);
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const columns = [
    {
      title: '编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
    },
    {
      title: '值',
      dataIndex: 'values',
      key: 'values',
      width: 200,
      render: (values) => (
        <>
          {values && values.length > 0 ? (
            <Button onClick={() => showModal(values)}>
              详情 ({values.length} 项)
            </Button>
          ) : (
            '无数据'
          )}
        </>
      ),
    }
  ];

  const modalColumns = [
    {
      title: '标签',
      dataIndex: 'label',
      key: 'label',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    }
  ];

  return (
    <div style={{padding: '10px'}}>
      <Card title="枚举字典管理">
        <Form form={form} onFinish={handleSearch}>
          <Space>
            <Form.Item name="dictCode" label="字典编码">
              <Input placeholder="请输入字典编码" allowClear />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />}>
                查询
              </Button>
            </Form.Item>
          </Space>
        </Form>
        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey="code"
          scroll={{ y: '30vh' }}
          pagination={{
            current: searchForm.current,
            pageSize: searchForm.size,
            total: total,
            showTotal: (total) => `共 ${total} 条数据`,
            showSizeChanger: true,
            pageSizeOptions: ['5','10', '20', '50', '100']
          }}
          onChange={handleTableChange}
        />
      </Card>

      <Modal
        title="详情"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={600}
      >
        <Table
          columns={modalColumns}
          dataSource={modalData}
          rowKey={(record, index) => index}
          pagination={false}
        />
      </Modal>
    </div>
  );
};

export default EnumDict;